package com.qsmx.qingqiuticket.app.delegate;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.ClickUtil;
import com.qsmx.core.util.CountDownTimerUtil;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateLoginMemBinding;
import com.qsmx.qingqiuticket.app.entity.LoginMemEntity;
import com.qsmx.qingqiuticket.app.event.LoginEvent;
import com.qsmx.qingqiuticket.app.event.QrScanEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionData;
import com.qsmx.qingqiuticket.app.fusion.FusionTag;
import com.qsmx.qingqiuticket.app.net.HttpUrl;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;

public class HomeLoginMemDelegate extends AtmosDelegate {

    DelegateLoginMemBinding mBindView;
    private CountDownTimerUtil backTimer;

    @Override
    public Object setLayout() {
        return R.layout.delegate_login_mem;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mBindView = DelegateLoginMemBinding.bind(rootView);
        FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
        FusionCode.QrIsLoading = false;
        startCountDownBackTime(60);
        mBindView.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSupportDelegate().pop();
                EventBus.getDefault().post(new LoginEvent(new Bundle()));
            }
        });

        try {
            if (StringUtil.isNotEmpty(FusionData.mAdvData.getBody().getLoginImage())) {
                Glide.with(requireContext()).load(FusionData.mAdvData.getBody().getLoginImage()).error(R.mipmap.default_login_img).fallback(R.mipmap.default_login_img).into(mBindView.ivBg);
            } else {
                Glide.with(requireContext()).load(R.mipmap.default_login_img).into(mBindView.ivBg);
            }
        } catch (Exception e) {
            Glide.with(requireContext()).load(R.mipmap.default_login_img).into(mBindView.ivBg);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQrScanEvent(QrScanEvent event) {
        if (event != null && event.getData() != null) {
            String memCode = event.getData().getString(FusionTag.QR_CODE);
            //todo 查询会员卡
//            checkCard("", qrCode);
//            onPayOrder(qrCode);

            loginMem(memCode);
        }
    }

    private void loginMem(String memCode) {
        DialogUtil.showLoadingDialog(getContext(), "正在登录，请稍候...");
        if (backTimer != null) {
            backTimer.cancel();
        }
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;

        JSONObject params = new JSONObject();
        params.put("membershipCode", memCode);

        HttpHelper.RestClientPostRaw(params, HttpUrl.LOGIN_MEM,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        DialogUtil.dismissLoadingDialog();
                        try {
                            Type type = new TypeToken<LoginMemEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            LoginMemEntity mData = gson.fromJson(response, type);
                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                FusionData.mMemData = mData.getBody();
                                showLongToast("登录成功");
                                getSupportDelegate().pop();
                                EventBus.getDefault().post(new LoginEvent(new Bundle()));
                            } else {
                                DialogUtil.showCardErrorDialog(getContext(), mData.getHeader().getMessage(), "确定");
                                FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                                FusionCode.QrIsLoading = false;
                                startCountDownBackTime(60);
                            }
                        } catch (Exception e) {
                            DialogUtil.showCardErrorDialog(getContext(), getString(R.string.service_error), "确定");
                            FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                            FusionCode.QrIsLoading = false;
                            startCountDownBackTime(60);
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(getContext(), msg, "确定");
                        FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                        FusionCode.QrIsLoading = false;
                        startCountDownBackTime(60);
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(getContext(), "网络错误", "确定");
                        FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                        FusionCode.QrIsLoading = false;
                        startCountDownBackTime(60);
                    }
                });

    }

    private void startCountDownBackTime(final long time) {
        if (backTimer != null) {
            backTimer.cancel();
        }
        backTimer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                mBindView.tvTime.setText(String.format(getString(R.string.back_time), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                getSupportDelegate().popTo(HomeDelegate.class, false);
            }
        };
        backTimer.start();// 开始计时
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        startCountDownBackTime(60);

    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        EventBus.getDefault().unregister(this);
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
        if (backTimer != null) {
            backTimer.cancel();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
        EventBus.getDefault().unregister(this);
        if (backTimer != null) {
            backTimer.cancel();
        }
        DialogUtil.dismissLoadingDialog();
        DialogUtil.dismissErrorDialog();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
}
